/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.SourceCode;
import pojos.SubcontarctorResources;
import pojos.JobsTitles;
import pojos.Projects;
import pojos.Employees;
import pojos.Currencies;

/**
 *
 * @author A7med Kotb
 */
public class SourceCodeJpaController implements Serializable {

    public SourceCodeJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(SourceCode sourceCode) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            SubcontarctorResources subcontResName = sourceCode.getSubcontResName();
            if (subcontResName != null) {
                subcontResName = em.getReference(subcontResName.getClass(), subcontResName.getSubResId());
                sourceCode.setSubcontResName(subcontResName);
            }
            JobsTitles role = sourceCode.getRole();
            if (role != null) {
                role = em.getReference(role.getClass(), role.getJobTitleId());
                sourceCode.setRole(role);
            }
            Projects projectCode = sourceCode.getProjectCode();
            if (projectCode != null) {
                projectCode = em.getReference(projectCode.getClass(), projectCode.getProId());
                sourceCode.setProjectCode(projectCode);
            }
            Employees employee = sourceCode.getEmployee();
            if (employee != null) {
                employee = em.getReference(employee.getClass(), employee.getEmpId());
                sourceCode.setEmployee(employee);
            }
            Currencies currency = sourceCode.getCurrency();
            if (currency != null) {
                currency = em.getReference(currency.getClass(), currency.getCurrId());
                sourceCode.setCurrency(currency);
            }
            em.persist(sourceCode);
            if (subcontResName != null) {
                subcontResName.getSourceCodeCollection().add(sourceCode);
                subcontResName = em.merge(subcontResName);
            }
            if (role != null) {
                role.getSourceCodeCollection().add(sourceCode);
                role = em.merge(role);
            }
            if (projectCode != null) {
                projectCode.getSourceCodeCollection().add(sourceCode);
                projectCode = em.merge(projectCode);
            }
            if (employee != null) {
                employee.getSourceCodeCollection().add(sourceCode);
                employee = em.merge(employee);
            }
            if (currency != null) {
                currency.getSourceCodeCollection().add(sourceCode);
                currency = em.merge(currency);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(SourceCode sourceCode) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            SourceCode persistentSourceCode = em.find(SourceCode.class, sourceCode.getScId());
            SubcontarctorResources subcontResNameOld = persistentSourceCode.getSubcontResName();
            SubcontarctorResources subcontResNameNew = sourceCode.getSubcontResName();
            JobsTitles roleOld = persistentSourceCode.getRole();
            JobsTitles roleNew = sourceCode.getRole();
            Projects projectCodeOld = persistentSourceCode.getProjectCode();
            Projects projectCodeNew = sourceCode.getProjectCode();
            Employees employeeOld = persistentSourceCode.getEmployee();
            Employees employeeNew = sourceCode.getEmployee();
            Currencies currencyOld = persistentSourceCode.getCurrency();
            Currencies currencyNew = sourceCode.getCurrency();
            if (subcontResNameNew != null) {
                subcontResNameNew = em.getReference(subcontResNameNew.getClass(), subcontResNameNew.getSubResId());
                sourceCode.setSubcontResName(subcontResNameNew);
            }
            if (roleNew != null) {
                roleNew = em.getReference(roleNew.getClass(), roleNew.getJobTitleId());
                sourceCode.setRole(roleNew);
            }
            if (projectCodeNew != null) {
                projectCodeNew = em.getReference(projectCodeNew.getClass(), projectCodeNew.getProId());
                sourceCode.setProjectCode(projectCodeNew);
            }
            if (employeeNew != null) {
                employeeNew = em.getReference(employeeNew.getClass(), employeeNew.getEmpId());
                sourceCode.setEmployee(employeeNew);
            }
            if (currencyNew != null) {
                currencyNew = em.getReference(currencyNew.getClass(), currencyNew.getCurrId());
                sourceCode.setCurrency(currencyNew);
            }
            sourceCode = em.merge(sourceCode);
            if (subcontResNameOld != null && !subcontResNameOld.equals(subcontResNameNew)) {
                subcontResNameOld.getSourceCodeCollection().remove(sourceCode);
                subcontResNameOld = em.merge(subcontResNameOld);
            }
            if (subcontResNameNew != null && !subcontResNameNew.equals(subcontResNameOld)) {
                subcontResNameNew.getSourceCodeCollection().add(sourceCode);
                subcontResNameNew = em.merge(subcontResNameNew);
            }
            if (roleOld != null && !roleOld.equals(roleNew)) {
                roleOld.getSourceCodeCollection().remove(sourceCode);
                roleOld = em.merge(roleOld);
            }
            if (roleNew != null && !roleNew.equals(roleOld)) {
                roleNew.getSourceCodeCollection().add(sourceCode);
                roleNew = em.merge(roleNew);
            }
            if (projectCodeOld != null && !projectCodeOld.equals(projectCodeNew)) {
                projectCodeOld.getSourceCodeCollection().remove(sourceCode);
                projectCodeOld = em.merge(projectCodeOld);
            }
            if (projectCodeNew != null && !projectCodeNew.equals(projectCodeOld)) {
                projectCodeNew.getSourceCodeCollection().add(sourceCode);
                projectCodeNew = em.merge(projectCodeNew);
            }
            if (employeeOld != null && !employeeOld.equals(employeeNew)) {
                employeeOld.getSourceCodeCollection().remove(sourceCode);
                employeeOld = em.merge(employeeOld);
            }
            if (employeeNew != null && !employeeNew.equals(employeeOld)) {
                employeeNew.getSourceCodeCollection().add(sourceCode);
                employeeNew = em.merge(employeeNew);
            }
            if (currencyOld != null && !currencyOld.equals(currencyNew)) {
                currencyOld.getSourceCodeCollection().remove(sourceCode);
                currencyOld = em.merge(currencyOld);
            }
            if (currencyNew != null && !currencyNew.equals(currencyOld)) {
                currencyNew.getSourceCodeCollection().add(sourceCode);
                currencyNew = em.merge(currencyNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = sourceCode.getScId();
                if (findSourceCode(id) == null) {
                    throw new NonexistentEntityException("The sourceCode with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            SourceCode sourceCode;
            try {
                sourceCode = em.getReference(SourceCode.class, id);
                sourceCode.getScId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The sourceCode with id " + id + " no longer exists.", enfe);
            }
            SubcontarctorResources subcontResName = sourceCode.getSubcontResName();
            if (subcontResName != null) {
                subcontResName.getSourceCodeCollection().remove(sourceCode);
                subcontResName = em.merge(subcontResName);
            }
            JobsTitles role = sourceCode.getRole();
            if (role != null) {
                role.getSourceCodeCollection().remove(sourceCode);
                role = em.merge(role);
            }
            Projects projectCode = sourceCode.getProjectCode();
            if (projectCode != null) {
                projectCode.getSourceCodeCollection().remove(sourceCode);
                projectCode = em.merge(projectCode);
            }
            Employees employee = sourceCode.getEmployee();
            if (employee != null) {
                employee.getSourceCodeCollection().remove(sourceCode);
                employee = em.merge(employee);
            }
            Currencies currency = sourceCode.getCurrency();
            if (currency != null) {
                currency.getSourceCodeCollection().remove(sourceCode);
                currency = em.merge(currency);
            }
            em.remove(sourceCode);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<SourceCode> findSourceCodeEntities() {
        return findSourceCodeEntities(true, -1, -1);
    }

    public List<SourceCode> findSourceCodeEntities(int maxResults, int firstResult) {
        return findSourceCodeEntities(false, maxResults, firstResult);
    }

    private List<SourceCode> findSourceCodeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(SourceCode.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public SourceCode findSourceCode(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(SourceCode.class, id);
        } finally {
            em.close();
        }
    }

    public int getSourceCodeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<SourceCode> rt = cq.from(SourceCode.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
